{
Function:       _SharpeRatioArray

Description:    Calculate Sharpe Ratio from price array.

                Use of price array avoids backreferencing price bars, which would require MaxBarsBack be
                set to an unacceptably large value when useing Sharpe Ratio to assess strategy performance.
                
                For example, if you calculate a 5 year Sharpe Ratio on on a daily chart by backreferencing
                Price bars, your MaxBarsBack would be 5 years of data, or 251 * 5 = 1255 daily bars.
                or 251 * 10 = 2510 bars.  If your chart was loaded with 10 years of data, only the This 
                would prevent your strategy from executing until MaxBarsBack of data had been loaded, 
                and then there would not be an additional 10 years of data available to run your strategy.

                Instead, by loading the Equity curve into an array on a daily basis, and then passing
                this array to this function, NO increase in MaxBarsBack is required for this array routine 
                to calculate the 10 year Sharpe Ratio.  
                
                Therefore, this routine would not add any additional MaxBarsBack requirement beyond 
                what the strategy already requires.

Author:         MarkSanDiego

Updated:        09/12/09    Original version.


USAGE: 

Add these variables to calling indicator:

inputs:                             { _SharpeRatioArray input parameters }
    SegLength(5),
    SegsPerYear(52),
    Segments(12),
    RiskFreeReturn(2.0);            { annualized risk free return in percent. }

vars:                               { for _SharpeRatio }
    avgRR(0),                       { average return rate for segments }
    sdRR(0),                        { standard deviation of return rates }
    annRR(0),                       { annualized rate of return = RR * 12 (1 segment = 1 month) }
    annSD(0),                       { annualized standard deviation of returns = sdRR * 12 (1 segment = 1 month) }
    excessRR(0),                    { excess return = annualized rate of return - risk free return }
    SR(0);                          { Sharpe Ratio }

arrays:
    EquityArray[5000](0);           { PriceArray to hold equity curve.  Dimensioned to backtest up to 5000 bars of data. }


        value1 = _SharpeRatioArray(EquityArray, EquityArraySize, DataBars, SegLength, SegsPerYear, Segments, 
            RiskFreeReturn, Offset, avgRR, sdRR, annRR, annSD, excessRR, SR); 

        value1                          { = 1 if calculations successful, = 0 if insufficient data to calculate SR }                
}
inputs: 
    PriceArray[xx](NumericArrayRef),    { circularly indexed PriceArray holding equity curve to be measured }
    PriceArraySize(NumericRef),         { total elements PriceArray }
    DataBars(NumericRef),               { total data points loaded into price array }
            
    SegsPerYear(NumericSimple),         { daily: 251; weekly: 52; monthly: 12 }
    SegLength(NumericSimple),           { if analysis based on daily: 1; weekly: 5; monthly: 20 }
    Segments(NumericSimple),            { bars processed to calculate Sharpe Ratio (days to process, weeks to process or months to process) }
    RiskFreeReturn(NumericSimple),
    Offset(NumericSimple),

{ outputs: } 
    avgRR(NumericRef),                  { average return rate for segments }
    sdRR(NumericRef),                   { standard deviation of return rates }
    annRR(NumericRef),                  { annualized rate of return = RR * 12 (if segment = 1 month, or = RR*52 if segment = 1 week) }
    annSD(NumericRef),                  { annualized standard deviation of returns = sdRR * SqRoot(SegsPerYear) (SqRoot(12) if segment = 1 month) }
    excessRR(NumericRef),               { excess return = annualized rate of return - risk free return }
    SR(NumericRef);                     { Sharpe Ratio = Excess return / annualized standard deviation of returns }

vars:
    j(0),                               { miscellaneous index or loop counter }
    k(0),                               { miscellaneous index or loop counter }
    m(0),                               { miscellaneous index or loop counter }
    n(0),                               { miscellaneous index or loop counter }
    mm(0),                              { miscellaneous index or loop counter }
    nn(0),                              { miscellaneous index or loop counter }
    SqrtSegsPerYear(SquareRoot(SegsPerYear)),   { square root of number of segments per year }  
    y(0),
    index(0),                           { index for circular array RR } 
    Start(0),                           { PriceArray index to start calculations }  
    FirstPass(True),
    Sum(0),
    OldestRR(0),
    SumSq(0),
    Diff(0);

 
arrays:
    RR[3000](0);                        { RR[i] = return rates for segment[i]  Note: static arrays are 20X faster than dynamic arrays  }
                                        { 10 years of weekly samples requires 52 * 10 = 520 array elements }

 
once begin
    
    { calculation of standard deviations of gains requires at least 2 segments }
    if Segments <= 1 then RaiseRunTimeError("Function _SharpeRatioArray: Segments must be > 1");
    if PriceArraySize < SegLength * Segments then 
        RaiseRunTimeError("Function _SharpeRatioArray: PriceArraySize must be > SegLength * Segments ( " + 
        NumToStr(SegLength,0) + " X " + NumToStr(Segments,0) + " = " + NumToStr(SegLength*Segments,0) + " )");

    avgRR = 0;
    sdRR = 0;
    annRR = 0;
    annSD = 0;
    excessRR = 0;
    SR = 0;
 
end;     

if DataBars > Segments * SegLength then begin                       { ensure sufficient data received to perform requested calculation }

    if SegLength > 1 or FirstPass then begin

        FirstPass = False;
        Sum = 0;

        Start = DataBars - Offset - SegLength * Segments;   { starting price offset to calculate rate of return }               

        for j = 1 to Segments begin                                 { load rates of return }
            m = Start + (j - 1) * SegLength;                        { starting price offset to calculate rate of return }
            n = m + SegLength;                                      { interval price offset to calculate rate of return }
            mm = _CircularIndex(m, PriceArraySize);                 { starting circular index in PriceArray }
            nn = _CircularIndex(n, PriceArraySize);                 { interval circular index in PriceArray }
            
            y = PriceArray[mm];
            if y <> 0 then RR[j] = (PriceArray[nn]/y - 1)*100
                else RR[j] = 0;
            Sum = Sum + RR[j];
        end;
 
        index = 0;
        avgRR = Sum / Segments;                                     { average rate of return of segments }

    end else begin                                                  { SegLength = 1, subsequent pass }
        
        index = index + 1;                                          { create circular index for array RR }
        if index > Segments then index = 1; 
        OldestRR = RR[index]; 

        m = CurrentBar - Offset;                                    { current price pointer }
        n = m - 1;                                                  { prior price bar pointer }
        mm = _CircularIndex(m, PriceArraySize);                     { current price circular index }
        nn = _CircularIndex(n, PriceArraySize);                     { prior price bar circular index }

        y = PriceArray[nn];
        if y <> 0 then RR[index] = (PriceArray[mm]/y - 1)*100 
            else RR[index] = 0;

        avgRR = avgRR[1] + ( RR[index] - OldestRR ) / Segments;     { average rate of return of segments }

    end;

    
    annRR = avgRR * SegsPerYear;                                    { annualized the rate of return }
//  excessRR = annRR - RiskFreeReturn;                              { original Sharpe Ratio formula }
    excessRR = annRR - Sign(annRR)*RiskFreeReturn;                  { modification: reverse sign on RiskFreeReturn if annRR is negative }
    
    SumSq = 0;                                                      { calculate SD of rates of returns }
    for j = 1 to Segments begin
        Diff = RR[j] - AvgRR;
        SumSq = SumSq + (Diff * Diff);
    end;
    sdRR = SquareRoot(SumSq/Segments);                              { variance assumes total population, not sample }
    
    annSD = sdRR * SqrtSegsPerYear;                                 { annualize the SD of the returns }
    if annSD <> 0 then SR = excessRR/annSD                          { calculate Sharpe Ratio }
        else SR = 0;

end;


    _SharpeRatioArray = SR; 
